﻿using System.IO;
using System.Net;
using System.Text;

namespace Foundation
{
    /// <summary>
    /// Web Helper.
    /// </summary>
    public static class WebHelper
    {
        /// <summary>
        /// HTTPs the get.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="proxy">The proxy.</param>
        /// <returns></returns>
        public static string HttpGet(string uri, string proxy = null)
        {
            var req = WebRequest.Create(uri);
            if (!string.IsNullOrWhiteSpace(proxy))
                req.Proxy = new WebProxy(proxy);
            var stream = req.GetResponse().GetResponseStream();
            return stream == null ? null : new StreamReader(stream).ReadToEnd().Trim();
        }

        /// <summary>
        /// HTTPs the post.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="data">The data.</param>
        /// <param name="proxy">The proxy.</param>
        /// <returns></returns>
        public static string HttpPost(string uri, string contentType, byte[] data, string proxy = null)
        {
            var req = WebRequest.Create(uri);
            if (!string.IsNullOrWhiteSpace(proxy))
                req.Proxy = new WebProxy(proxy);
            //Add these, as we're doing a POST
            req.ContentType = contentType;
            req.Method = "POST";
            //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
            req.ContentLength = data.Length;
            var os = req.GetRequestStream();
            os.Write(data, 0, data.Length); //Push it out there
            os.Close();
            var stream = req.GetResponse().GetResponseStream();
            return stream == null ? null : new StreamReader(stream).ReadToEnd().Trim();
        }

        /// <summary>
        /// HTTPs the post.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="proxy">The proxy.</param>
        /// <returns></returns>
        public static string HttpPost(string uri, string contentType, string parameters, string proxy = null)
        {
            var data = Encoding.UTF8.GetBytes(parameters);
            return HttpPost(uri, contentType, data, proxy);
        }
    }
}
